package com.yeyaomai.dksns.flowis.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yeyaomai.dksns.flowis.domain.VisitArea;
import com.yeyaomai.dksns.flowis.service.DownExcelService;
import com.yeyaomai.dksns.flowis.service.VisitAreaService;
import com.yeyaomai.dksns.flowis.service.result.DynamicXml;
import com.yeyaomai.dksns.flowis.util.Globals;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

@Controller
@RequestMapping("/visitarea/*")
public class VisitAreaController {

	@Autowired
	private VisitAreaService visitAreaService;

	@Autowired
	private DownExcelService downExcelService;

	@RequestMapping(value = "/detail")
	public ModelAndView getTodayCount(HttpServletRequest request)
			throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		String formDate = request.getParameter("formDate");
		String toDate = request.getParameter("toDate");
		String number = request.getParameter("number");
		String type = request.getParameter("type");
		String dateCount = request.getParameter("dateCount");
		String date = formDate;
		map.put("dateCount", 2);
		ModelAndView view = new ModelAndView("visit-area");
		view.addObject("formDate", formDate);
		view.addObject("toDate", toDate);
		view.addObject("type", type);
		view.addObject("nowDate", Globals.FORMAT_TYPE_A.format(new Date()));
		view.addObject(
				"month",
				VelocityToolDateUtils.getDay(Integer.valueOf("-"
						+ Globals.FORMAT_TYPE_D.format(new Date())) + 1));
		if (dateCount.equals("1")) {
			map.put("dateCount", 1);
		}
		toDate = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);
		map.put("fromReferDay", date);
		map.put("toReferDay", toDate);
		VisitArea visitArea = new VisitArea();
		visitArea = visitAreaService.getVisitAreaByTime(date, toDate);
		Page<VisitArea> result = visitAreaService.getDataPage(map,
				Integer.valueOf(number));
		view.addObject("result", result);
		view.addObject("number", number);
		view.addObject("visit", visitArea);
		view.addObject("dateCount", dateCount);
		return view;
	}

	@RequestMapping(value = "/chinaxml")
	public void changeXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("toDate") String toDate, HttpServletResponse response)
			throws IOException, ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Integer> visitMap = new HashMap<String, Integer>();
		visitMap.put("北京市", 0);
		visitMap.put("河北省", 0);
		visitMap.put("天津市", 0);
		visitMap.put("广东省", 0);
		visitMap.put("广西", 0);
		visitMap.put("内蒙古", 0);
		visitMap.put("安徽省", 0);
		visitMap.put("重庆市", 0);
		visitMap.put("福建省", 0);
		visitMap.put("甘肃省", 0);
		visitMap.put("贵州省", 0);
		visitMap.put("海南省", 0);
		visitMap.put("河南省", 0);
		visitMap.put("湖北省", 0);
		visitMap.put("黑龙江省", 0);
		visitMap.put("湖南省", 0);
		visitMap.put("江苏省", 0);
		visitMap.put("江西省", 0);
		visitMap.put("吉林省", 0);
		visitMap.put("辽宁省", 0);
		visitMap.put("宁夏", 0);
		visitMap.put("青海省", 0);
		visitMap.put("陕西省", 0);
		visitMap.put("山东省", 0);
		visitMap.put("山西省", 0);
		visitMap.put("上海市", 0);
		visitMap.put("四川省", 0);
		visitMap.put("新疆", 0);
		visitMap.put("西藏", 0);
		visitMap.put("云南省", 0);
		visitMap.put("浙江省", 0);
		visitMap.put("香港", 0);
		visitMap.put("澳门", 0);
		visitMap.put("台湾省", 0);
		List<VisitArea> visitArea = new ArrayList<VisitArea>();
		map.put("dateCount", 2);
		String date = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);
		map.put("fromReferDay", fromDate);
		map.put("toReferDay", date);
		map.put("startNumber", null);
		map.put("endNumber", null);
		visitArea = visitAreaService.getVisitAreaByDay(map);
		int maxValue = 0;
		for (int i = 0; i < visitArea.size(); i++) {
			maxValue = visitArea.get(0).getVisitCount();
			if (maxValue < visitArea.get(i).getVisitCount()) {
				maxValue = visitArea.get(i).getVisitCount();
			}
			visitMap.put(visitArea.get(i).getProvince(), visitArea.get(i)
					.getVisitCount());
		}
		String xml = DynamicXml.getVisitAreaMap(visitMap, maxValue);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}

	@RequestMapping(value = "/visitpiexml")
	public void changePieXml(@RequestParam("fromDate") String fromDate,
			@RequestParam("toDate") String toDate, HttpServletResponse response)
			throws ParseException, IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		List<VisitArea> visitArea = new ArrayList<VisitArea>();
		map.put("dateCount", 2);
		String date = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(
				toDate).getTime()
				+ 1 * 24 * 3600 * 1000);
		map.put("fromReferDay", fromDate);
		map.put("toReferDay", date);
		map.put("startNumber", null);
		map.put("endNumber", null);
		visitArea = visitAreaService.getVisitAreaByDay(map);
		String xml = DynamicXml.getVisitAreaPie(visitArea);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}

	/**
	 * 来路域名历史数据展示
	 * 
	 * @param request
	 * @return
	 * @throws ParseException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/history")
	public ModelAndView getVisitAreaByProvince(HttpServletRequest request)
			throws ParseException, UnsupportedEncodingException {
		String province = URLDecoder.decode(request.getParameter("province"),
				"UTF-8");
		String toDate = request.getParameter("date");
		Date date = Globals.FORMAT_TYPE_A.parse(toDate);
		Date d = null;
		String type = request.getParameter("type");
		String fromDate = "";
		if (type.equals("-1")) {
			d = DateUtils.truncate(DateUtils.addDays(date, -30), Calendar.DATE);
			fromDate = Globals.FORMAT_TYPE_A.format(d);
		} else if (type.equals("1")) {
			d = DateUtils.truncate(DateUtils.addDays(date, 30), Calendar.DATE);
			String middle = toDate;
			toDate = Globals.FORMAT_TYPE_A.format(d);
			fromDate = middle;
		}
		String currentTime = Globals.FORMAT_TYPE_A.format(new Date());
		ModelAndView view = new ModelAndView("visitarea-history");

		if ((Globals.FORMAT_TYPE_A.parse(toDate).getTime()) >= (Globals.FORMAT_TYPE_A
				.parse(currentTime).getTime())) {
			view.addObject("show", 1);
		} else {
			view.addObject("show", 0);
		}
		view.addObject("province", URLEncoder.encode(province, "UTF-8"));
		view.addObject("provinceName", province);
		view.addObject("currentDate", currentTime);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("province", province);
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);
		List<VisitArea> visitList = new ArrayList<VisitArea>();
		visitList = visitAreaService.getVisitAreaByProvince(map);
		view.addObject("visitList", visitList);
		view.addObject("fromDate", fromDate);
		view.addObject("toDate", toDate);
		return view;
	}

	/**
	 * 地区分布历史柱状图展示
	 * 
	 * @param fromDate
	 *            开始时间
	 * @param value
	 *            类型
	 * @param toDate
	 *            结束时间
	 * @param province
	 *            省份
	 * @param response
	 *            返回拼装数据
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping(value = "/visithistoryxml")
	public void changeVisitAreaHistoryXml(
			@RequestParam("fromDate") String fromDate,
			@RequestParam("value") String value,
			@RequestParam("toDate") String toDate,
			@RequestParam("province") String province,
			HttpServletResponse response) throws IOException, ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("province", URLDecoder.decode(province, "UTF-8"));
		map.put("fromDate", fromDate);
		map.put("toDate", toDate);

		List<VisitArea> visitList = visitAreaService
				.getVisitAreaByProvince(map);
		String xml = DynamicXml.getColumnByVisitArea(visitList, value,
				fromDate, toDate);

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}

	// 地区报表下载
	@RequestMapping(value = "down")
	public void download(HttpServletRequest request,
			HttpServletResponse response) throws ParseException,
			UnsupportedEncodingException {

		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String dateCount = request.getParameter("dateCount");
		String todate = Globals.FORMAT_TYPE_A.format(Globals.FORMAT_TYPE_A.parse(endTime).getTime() + 1 * 24 * 3600 * 1000);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fromReferDay", startTime);
		map.put("toReferDay", todate);
		map.put("startNumber", null);
		map.put("endNumber", null);
		map.put("dateCount", dateCount);
		List<VisitArea> visitAreaList = visitAreaService.getVisitAreaByDay(map);

		String title = "地域分布(" + startTime + "至" + endTime + ")";
		String newTitle = URLEncoder.encode(title, "UTF-8");

		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename="
				+ newTitle + ".xls");

		List<String> heads = new ArrayList<String>();
		heads.add("日期");
		if(dateCount.equals("1"))
		{
			heads.add("市");
		}
		if(dateCount.equals("2"))
		{
			heads.add("省");
		}
		heads.add("访问次数");
		heads.add("独立访客");
		heads.add("ip");
		heads.add("新独立访客");
		List<String> pros = new ArrayList<String>();
		pros.add("referDate");
		if(dateCount.equals("1"))
		{
			pros.add("city");
		}
		if(dateCount.equals("2"))
		{
			pros.add("province");
		}
		pros.add("visitCount");
		pros.add("uniqueHost");
		pros.add("ip");
		pros.add("newUniqueHost");
		try {
			downExcelService.exportExcel(title, heads, visitAreaList,
					response.getOutputStream(), pros);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
